<script setup lang="ts">
import { Toast } from '@/utils/tools'
import { computed, onUpdated, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  checkCodeApi,
  getCodeApi,
  getPayPasswordFreeApi,
  setPayPasswordApi,
  updatePayPasswordFreeApi,
} from '@/services/wallet'
import { useMemberStore } from '@/stores'
import Password from '@/components/Password.vue'
import PasswordPopup from '@/components/passwordPopup.vue'

// 获取胶囊的距离
const top = ref('') //上方距离
const pageheight = ref('') //整个导航栏高度
const height = ref('') //实际导航栏高度

const memberStore = useMemberStore() // 本地缓存

const passwordPopupRef = ref<{
  open: () => void
  close: () => void
}>()

const isOpen = ref<number>(0)
const PasswordRef = ref()
// 重置密码
const isReset = ref(false)
// 设置密码
const isSetting = ref(false)
// 手机号码验证
const isCode = ref(false)
// 订单详情页面进来返回上一页
const isBack = ref(false)
// 开启关闭免密支付
async function handleSecretFree() {
  if (isOpen.value) {
    const res = await updatePayPasswordFreeApi({
      payPasswordFree: 0,
    })
    if (res.code === 200) {
      getPayPasswordFree()
    }
    return
  }
  passwordPopupRef.value?.open()
}

// 是否开启免密支付
async function getPayPasswordFree() {
  const res = await getPayPasswordFreeApi()
  if (res.code === 200) {
    isOpen.value = res?.data
    memberStore.setHasPayPasswordFree(res?.data)
  }
}

// 充值设置密码后重置状态
async function handleResetInput(inputList: number[], type: string) {
  if (isBack.value) {
    //返回上一页
    uni.navigateBack()
  }
  isSetting.value = false
  isReset.value = false
  Toast(`支付密码${type === 'isSetting' ? '设置' : '重置'}成功`)
}

// 开启关闭免密支付
async function handleInput(inputList: number[]) {
  const res = await updatePayPasswordFreeApi({
    payPasswordFree: isOpen.value ? 0 : 1,
    password: inputList.join(''),
  })
  if (res.code === 200) {
    getPayPasswordFree()
    passwordPopupRef.value?.close()
    console.log('inputList', inputList)
  }
}

// 格式化手机号
function formatMobile() {
  var mobile = memberStore.userInfo?.mobile
  mobile = '' + mobile
  return mobile.replace(mobile.substring(3, 7), '****')
}

/**
 * * 验证码输入框聚焦事件
 */
const formData = reactive({
  code: '',
  phone: '18637294658',
})
let disabled = ref(false)
const isFocus = ref(false) // 点击验证码的时候，验证码输入框获取焦点
let codeTime = ref(0) // 显示在验证码上面的时间
// 点击按钮发送验证码
const onCode = async () => {
  // 调用验证码接口
  const res = await getCodeApi()
  if (res.code === 200) {
    countDownFn(60) // 输入的时间
    Toast('验证码已发送')
  }
}

const timeOut = ref()
/**
 * * 倒计时方法
 */
const countDownFn = (times: number) => {
  codeTime.value = times
  disabled.value = true // 关闭 获取验证码 按钮
  isFocus.value = true // 开启 验证码input 的聚焦
  if (codeTime.value <= 0) {
    codeTime.value = times
  }
  // 倒计时时间
  timeOut.value = setInterval(() => {
    codeTime.value-- // 时间自减
    //  倒计时为0 的时候把倒计时清掉，并且开启按钮
    if (codeTime.value === 0) {
      disabled.value = false // 开启 获取验证码 按钮
      isFocus.value = false // 关闭聚焦
      clearInterval(timeOut.value)
    }
  }, 1000)
}
const buttonText = computed(() => {
  if (codeTime.value > 0) {
    return `${codeTime.value}秒后重发`
  } else {
    return `获取验证码`
  }
})
// 验证码按钮框是否禁用
onUpdated(() => {
  console.log('disabled.value', disabled.value)
  // 验证码的时间是否归零
  if (codeTime.value === 0) {
    console.log('disabled.value1', disabled.value)
    disabled.value = false
  } else {
    console.log('disabled.value2', disabled.value)
    disabled.value = true
  }
})

// 下一步
async function onSubmit() {
  if (!formData.code) {
    Toast('请输入验证码')
  } else if (formData.code.length < 4) {
    Toast('请输入正确的验证码')
  } else {
    const res = await checkCodeApi({ code: formData.code })
    if (res?.data && res.code === 200) {
      console.log('111111', 111111)
      isReset.value = true
      isCode.value = false
      clearInterval(timeOut.value)
      codeTime.value = 0
      disabled.value = false
      formData.code = ''
    }
  }
}

// 点击返回按钮
function handleBack(type?: string) {
  console.log('type', type)
  console.log('1', 1)
  if (type === 'code') {
    console.log(' 输入验证码之后 重置密码页面点击返回')
    // 输入验证码之后 重置密码页面点击返回
    isCode.value = true
    isReset.value = false
    isSetting.value = false
  } else if (isCode.value) {
    // 重置密码获取验证码阶段
    console.log(' 重置密码获取验证码阶段')
    formData.code = ''
    isCode.value = false
    clearInterval(timeOut.value)
    codeTime.value = 0
    disabled.value = false
  } else if (isReset.value || isSetting.value) {
    console.log('isReset.value || isSetting.value', isReset.value || isSetting.value)
    PasswordRef.value?.handleBack()
  } else {
    console.log('uni.navigateBack()', uni.navigateBack())
    uni.navigateBack()
  }
}

onLoad((options: any) => {
  const res = uni.getMenuButtonBoundingClientRect() //获取胶囊
  top.value = res.top + 'px'
  pageheight.value = res.height + 10 + res.top + 'px'
  height.value = res.height + 'px'
  console.log('获取胶囊位置', height.value)
  if (options.isSetting === '1') {
    isSetting.value = true
  }
  if (options.isBack) {
    isBack.value = true
  }
  getPayPasswordFree()
})
</script>
<template>
  <view>
    <view class="tab_set">
      <!-- 设置胶囊顶部 -->
      <view class="MenuButton_top"></view>
      <!-- 实际导航栏 可封装自定义组件  -->
      <view class="back_Tag">
        <uni-icons type="left" size="22" color="#00000090" @click="handleBack"></uni-icons
        ><text class="title">支付密码</text></view
      >
    </view>
    <view
      class="container"
      :style="isReset || isSetting || isCode ? 'background: #fff;' : 'background: #F5F5F5;'"
    >
      <view class="cells" v-show="!isReset && !isSetting && !isCode">
        <view class="item">
          <view class="label">免密支付</view>
          <image v-show="!isOpen" @click="handleSecretFree" src="/static/images/closeSwitch.png" />
          <image v-show="isOpen" @click="handleSecretFree" src="/static/images/openSwitch.png" />
        </view>
        <view class="item">
          <view class="label">重置支付密码</view>
          <view class="iconfont icon_arrow-left-1" @click="isCode = true"></view>
        </view>
      </view>

      <PasswordPopup ref="passwordPopupRef" @finish="handleInput" />
      <Password
        v-if="isReset || isSetting"
        ref="PasswordRef"
        :isSetting="isSetting"
        :isReset="isReset"
        @finish="handleResetInput"
        @back="handleBack"
      />
      <view class="codeWrapper" v-if="isCode">
        <view class="title">验证绑定手机号</view>
        <view class="desc">检测到您当前登录的手机号码为：</view>
        <view class="phone">{{ formatMobile() }}</view>
        <uni-forms class="uni-forms">
          <uni-forms-item name="code">
            <input
              :always-embed="true"
              type="number"
              :focus="!isFocus"
              v-model.trim="formData.code"
              class="forms_code"
              :maxlength="4"
              placeholder="请输入您的验证码"
              placeholder-style="color: rgba(0, 0, 0, 0.30);font-size: 30rpx;line-height: 66rpx"
            />
            <view class="button_box">
              <button
                class="button_code"
                :disabled="disabled"
                :class="disabled ? 'disabled' : ''"
                @click="onCode"
              >
                {{ buttonText + disabled }}{{ disabled }}
              </button>
            </view>
          </uni-forms-item>
          <button
            class="forms_button"
            :disabled="formData.code ? false : true"
            @click="onSubmit"
            :style="formData.code ? '' : 'background: rgba(0, 0, 0, 0.15);'"
          >
            下一步
          </button>
        </uni-forms>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  background-color: $uni-bg-color-grey;
  height: 100vh;
  width: 100%;
}
.cells {
  padding: 24rpx;
}
.item {
  padding: 28rpx 36rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: rgba(0, 0, 0, 0.9);
  font-family: 'PingFang SC';
  font-size: 28rpx;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  border-radius: 16rpx;
  background: #fff;
  margin-bottom: 20rpx;
  image {
    width: 116rpx;
    height: 60rpx;
  }
}
.codeWrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .title {
    color: #FFBD2C;
    font-family: 'PingFang SC';
    font-size: 40rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    margin-top: 100rpx;
  }

  .desc {
    color: rgba(0, 0, 0, 0.3);
    font-family: 'PingFang SC';
    font-size: 28rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    margin: 30rpx 0 40rpx;
  }
  .phone {
    color: #000;
    font-family: 'PingFang SC';
    font-size: 44rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }
  ::v-deep .uni-forms {
    margin-top: 117rpx;
    width: 700rpx;
    .uni-forms-item__content {
      width: 100%;
      height: 88rpx;
      padding: 12rpx 200rpx 12rpx 30rpx;
      display: flex;
      align-items: center;
      .button_box {
        position: absolute;
        top: 12rpx;
        right: 0;
        width: 200rpx;
        height: 66rpx;
        border-radius: 44rpx;
        .button_code {
          width: 100%;
          height: 100%;
          text-align: center;
          line-height: 66rpx;
          color: #fff;
          font-family: 'PingFang SC';
          font-size: 26rpx;
          font-style: normal;
          font-weight: 400;
          border-radius: 44rpx;
          background: #FFBD2C;
        }
        .disabled {
          background: rgba(0, 0, 0, 0.15);
        }
      }
      .forms_code {
        line-height: 66rpx;
      }
    }
    .forms_button {
      border-radius: 44rpx;
      background: #FFBD2C;
      color: #fff;
      text-align: center;
      font-family: 'PingFang SC';
      font-size: 26rpx;
      font-style: normal;
      font-weight: 400;
      line-height: 84rpx;
      width: 700rpx;
      height: 84rpx;
      margin-top: 80rpx;
    }
  }
}

// 整个导航栏样式
.tab_set {
  // background: linear-gradient(rgb(82, 82, 247), rgb(218, 218, 248));
  height: v-bind('pageheight');
  position: relative;

  // 上方距离空隙
  .MenuButton_top {
    height: v-bind('top');
  }

  // 内部导航栏
  .back_Tag {
    height: v-bind('height');
    line-height: v-bind('height');
    // font-size: 20px;
    font-weight: 700;
    margin-left: 10rpx;
    font-weight: 400;
    position: relative;
    .title {
      position: absolute;
      left: 50%;
      top: 0;
      height: v-bind('height');
      line-height: v-bind('height');
      width: 100%;
      text-align: center;
      z-index: 99px;
      width: 200rpx;
      transform: translate3d(-50%, 0, 0);
    }
  }
}
</style>
